<template>
	<view class="index-page">
		<u-loading-page 
		:loading="loading" 
		color="#3c9cff" 
		bg-color="#515151" 
		loadingText="登录中"
		:fontSize="17"
		:iconSize="50">
		</u-loading-page>
	</view>
</template>

<script>
	import $storage from '@/utils/storage.js'
	
	import { login, userInfo } from '../../api/user.js'
	
	export default {
		name: 'IndexPage',
		data() {
			return {
				loading: true
			}
		},
		
		onLoad() {
			this.$nextTick(()=> {
				const userLoginToken = $storage.getTokenStorage()
				if(userLoginToken && userLoginToken != ''&& userLoginToken.length > 0){
					this.toMain()
				}else {
					this.wxLogin()
				}
			})
		},
		methods: {
			// 微信登录
			async wxLogin() {
				wx.login({
					success: async (res)=> {
						const loginInfo = await login({ wxCode: res.code })
						if(loginInfo.code !== 200){
							this.toLogin()
						}else {
							
							const loginToken = loginInfo.data.token
							await $storage.setTokenStorage(loginToken)
							this.toMain()
						}
						this.loading = false
					}
				})
			},
			
			// 加载用户信息
			async loadLoginInfo() {
				const loginInfo = await userInfo()
				$storage.setUserStorage(loginInfo.data)
			},
			
			// 跳转到登录
			toLogin() {
				uni.navigateTo({
					url: '/pages/login/index'
				})
			},
		
			// 跳转到首页
			async toMain() {
				await this.loadLoginInfo()
				uni.navigateTo({
					url: '/pages/main/main'
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	.index-page {
		margin: 200px auto;
	}
</style>
